package org.ting.book.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.ting.book.component.ResultFail;
import org.ting.book.component.ResultGenerator;
import org.ting.book.component.ResultSuccess;
import org.ting.book.model.BookInfo;
import org.ting.book.model.BorrowRecord;
import org.ting.book.model.Result;
import org.ting.book.service.BookService;
import org.ting.book.service.BorrowService;

import java.util.List;
@Slf4j
@RestController
@RequestMapping("/borrow")
public class BorrowController {
    @Autowired
    BookService bookService;
    @Autowired
    BorrowService borrowService;
    @RequestMapping("/borrow")
    public Result<?> borrow(Integer userId, Integer bookId) {
        return borrowService.borrowBook(userId, bookId);
    }

    @RequestMapping("/getRecord")
    public List<BorrowRecord> getRecord(Integer userId) {
        List<BorrowRecord> result =  borrowService.getRecordByUserId(userId);
        //回表查询图书信息,处理返回结果
        for(BorrowRecord borrowRecord : result) {
            BookInfo bookInfo = bookService.getBookById(borrowRecord.getBookId());
            borrowRecord.setBookName(bookInfo.getBookName());
            borrowRecord.setAuthor(bookInfo.getAuthor());
            borrowRecord.setPrice(bookInfo.getPrice());
            borrowRecord.setPublish(bookInfo.getPublish());
        }
        return result;
    }


    @RequestMapping("/returnBook")
    public Result<?> returnBook(Integer recordId) {
        log.info("recordId: " + recordId);
        return borrowService.returnBook(recordId);
    }
}
